package services

import (
	"360/video-srv/basic/config"
	__ "360/video-srv/basic/proto"
	"360/video-srv/modler"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"strconv"
)

func (s *Server) EsSync(_ context.Context, in *__.EsSyncReq) (*__.EsSyncResp, error) {
	var video modler.Video
	config.DB.Debug().Where("id = ?", in.VideoId).Find(&video)
	data, err := json.Marshal(&video)
	if err != nil {
		log.Fatalf("Error marshaling document: %s", err)
	}

	// Set up the request object.
	req := esapi.IndexRequest{
		Index:      "video",
		DocumentID: strconv.Itoa(int(video.ID)),
		Body:       bytes.NewReader(data),
		Refresh:    "true",
	}

	// Perform the request with the client.
	res, err := req.Do(context.Background(), config.Es)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	return &__.EsSyncResp{}, nil
}
func (s *Server) EsSearch(_ context.Context, in *__.EsSearchReq) (*__.EsSearchResp, error) {
	var keyword = in.KeyWord
	var buf bytes.Buffer
	query := map[string]interface{}{
		"query": map[string]interface{}{
			"match": map[string]interface{}{
				"title": keyword,
			},
		},
	}
	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	es := config.Es
	res, err := es.Search(
		es.Search.WithContext(context.Background()),
		es.Search.WithIndex("video"),
		es.Search.WithBody(&buf),
		es.Search.WithTrackTotalHits(true),
		es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()
	fmt.Println(&res)
	var r map[string]interface{}
	if err := json.NewDecoder(res.Body).Decode(&r); err != nil {
		log.Fatalf("Error parsing the response body: %s", err)
	}
	var b []*__.EsItem
	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		source := hit.(map[string]interface{})["_source"].(map[string]interface{})
		list := __.EsItem{
			Title:       source["title"].(string),
			Description: source["description"].(string),
			CoverUrl:    source["cover_url"].(string),
			Category:    source["category"].(string),
			Types:       source["types"].(string),
			Region:      source["region"].(string),
		}
		b = append(b, &list)
	}

	return &__.EsSearchResp{
		List: b,
	}, nil
}
